package io.github.fb513.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    private static final Algorithm algorithm;
    private static final Map<String, Object> header;
    private static final JWTVerifier verifier;

    static {
        algorithm = Algorithm.HMAC256("ajfaljawohlakj2qr0@)U$05ru20u)ur)qejjgoiporju)uajaup120LJFAPP240280U4101!#)u!)gqhipt");
        header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        verifier = JWT.require(algorithm).build();
    }

    public static String createToken(Map<String, Object> param) {
        LocalDateTime expireDate = LocalDateTime.now().plusHours(2);
        return createToken(param, DateUtils.asDate(expireDate));
    }

    public static String createToken(Map<String, Object> params, Date expireTime) {
        var builder = JWT.create().withHeader(header);
        // 设置 载荷 Payload
        builder.withClaim("params", params);
        return builder
                // 生成签名的时间
                .withIssuedAt(new Date())
                // 签名过期的时间
                .withExpiresAt(expireTime)
                // 签名Signature
                .sign(algorithm);
    }

    public static Map<String, Object> verifyToken(String token) {
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        Claim claim = claims.get("params");
        return claim.asMap();
    }
}
